package 剑指offer;

import 抽象数据类型.ListNode;

/**
 * @description:
 * @author: ywk
 * @date: 2021-04-03
 */
public class 环形链表的约瑟夫问题 {
    /**
     * @param n int整型
     * @param m int整型
     * @return int整型
     */
    public static int ysf(int n, int m) {
        // write code here
        if (n == 1) {
            return n;
        }
        if (m == 1) {
            return n;
        }
        int num = n;
        int count = 0;
        boolean[] exit = new boolean[n];
        int preIndex = 0;
        int i = 0;
        while (true) {
            if (exit[i] == true) {
                i++;
                i = i % n;
                continue;
            }
            count++;
            if (count == m) {
                count = 0;
                exit[i] = true;
                num--;
            }
            if (num == 1) {
                return preIndex + 1;
            }
            preIndex = i;
            i++;
            i = i % n;
        }
    }

    public static int ysfL(int n, int m) {
        ListNode head = new ListNode(1);
        ListNode tail = head;
        if (n == 1) {
            return n;
        }
        if (m == 1) {
            return n;
        }
        for (int i = 2; i <= n; i++) {
            tail.next = new ListNode(i);
            tail = tail.next;
        }
        tail.next = head;
        int count = n;
        int index = 0;
        ListNode curNode = head;
        ListNode preNode = head;
        while (count != 1) {
            index++;
            if (index % m == 0) {
                count--;
                preNode.next = curNode.next;
                curNode = curNode.next;
            } else {
                preNode = curNode;
                curNode = curNode.next;
            }
        }
        return curNode.val;
    }

    public static void main(String[] args) {
        System.out.println(ysf(5, 3));
        System.out.println(ysfL(5, 3));
    }
}
